<?php
//Baokim Payment Notification (BPN) Sample
// Ket noi database
include_once 'config.php';
include_once 'BaoKimPayment.php';
$db =mysql_connect(DB_HOSTNAME,DB_USERNAME,DB_PASSWORD) or die("Die connect: ".mysql_error());

mysql_select_db(DB_DATABASE) or die("Die select database: ".mysql_error());	

mysql_query("SET NAMES 'utf8'", $db);

//Lay thong tin tu Baokim POST sang
//Thuc hien  ghi log cac tin nhan BPN
$req = '';

foreach ( $_POST as $key => $value ) {

	$value = urlencode ( stripslashes ( $value ) );
	
	$req .= "&$key=$value";
	
}

$myFile = "bpn.log";

$fh = fopen($myFile, 'a') or die("can't open file");

fwrite($fh, $req);

$ch = curl_init();

//Dia chi chay BPN that
curl_setopt($ch, CURLOPT_URL,'https://www.baokim.vn/bpn/verify');
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
$error = curl_error($ch);

if($result != '' && strstr($result,'VERIFIED') && $status==200){

//Mot so thong tin khach hang khac
	fwrite($fh, ' => VERIFIED');	
	
	$order_id = $_POST['order_id'];
	
	$transaction_id = $_POST['transaction_id'];
	
	$transaction_status = $_POST['transaction_status'];
	
	$total_amount= $_POST['total_amount'];
	
	$net_amount= $_POST['net_amount'];
	
	$fee_amount= $_POST['fee_amount'];
	
	$customer_name= $_POST['customer_name'];
	
	$customer_name = $_POST['customer_name'];
	
	$customer_address = $_POST['customer_address'];
	
	//...
	//Nghiep vu: kiem tra xem order_id nay co ton tai trong he thong khong
	/**
	 * Neu co thi update thong tin thanh toan vao
	 */
	//update thong tin thanh toan! M? t? c?c tr?ng th?i transaction_status trong b?n DOC d?nh k?m
	
	//kiem tra trang thai giao dich
	if ($transaction_status == 4||$transaction_status == 13){
	
		//$update_query  	= "UPDATE ".DB_PREFIX."orders SET orders_status_id = '5' WHERE orders_id = '".$order_id."' ";
		
		//$exe_query		= "insert into `toc_orders_status_history` values ('','".$order_id."','5',now(),0,'')";	
		
		//mysql_query($update_query);
		
	}
	
	/**
	 * Neu khong thi bo qua
	 */
}else{
	fwrite($fh, ' => INVALID');
}

if ($error){
	fwrite($fh, " | ERROR: $error");
}
fwrite($fh, "\r\n");
fclose($fh);
?>